package com.generator.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.generator.annotations.MyRedisCache;
import com.generator.entities.User;
import com.generator.service.UserService;
import com.generator.mapper.UserMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;

/**
* @author 28146
* @description 针对表【t_user(用户表)】的数据库操作Service实现
* @createDate 2025-07-31 10:17:09
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

  public static final String CACHE_KEY_USER = "user:";

        @Resource
        private UserMapper userMapper;
        @Resource
        private RedisTemplate redisTemplate;


        @Override
        public boolean save(User user)
        {
            boolean retValue = false;

            log.info("插入之前user:{}", user);
            retValue = super.save(user);
            log.info("插入之后user:{}", user);
            log.info("=================================");

            if (retValue) {
                //到数据库里面，重新捞出新数据出来，做缓存
                user = this.userMapper.selectById(user.getId());
                //缓存key
                String key = CACHE_KEY_USER + user.getId();
                //往mysql里面插入成功随后再从mysql查询出来，再插入redis
                redisTemplate.opsForValue().set(key, user);
            }

            return retValue;
        }

        @Override
        @MyRedisCache(keyPrefix = "user",matchValue = "#id")
        public User getById(Serializable id)
        {
            //从mysql查出来user 如何将缓存代码从业务代码中剥离，促使业务代码更简洁更易维护
            return this.userMapper.selectById(id);
        }
    }






